package com.gmrz.uap.model;

import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.DBCommon;
import com.gmrz.uap.model.base.BaseResource;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Resource extends BaseResource<Resource> {
    public static final Resource dao = new Resource();

    public static final Logger LOG = LogManager.getLogger(Resource.class);
    public static final String NAMESPACE = "resource";
    private static final String SQL_SELECT_COMM = NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "select_comm";
    public static final String SQL_SELECT_USERID_PID = NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "findByUserIdAndPid";

    /**
     * 根据页面传过来的条件进行分页查询
     *
     * @param resource 资源信息
     * @param page     页号
     * @param rows     行数
     * @param sort     排序字段
     * @param order    升序/降序
     * @return　分页结果 Page<resource>
     */
    public Page<Resource> findListForPaginate(Resource resource, int page, int rows, String sort, String order) {

        StringBuffer sql = new StringBuffer();

        sql.append("from t_resource where resource_id=resource_id ");

        Iterator i = resource._getAttrsEntrySet().iterator();

        //循环遍历传过来的参数，并将参数拼接到SQL
        while (i.hasNext()) {
            Map.Entry<String, Object> obj = (Map.Entry<String, Object>) i.next();

            if (StrKit.isBlank(obj.getKey())) continue;

            if (StringUtils.equalsIgnoreCase("resource_id", obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = " + obj.getValue());
                continue;
            }

            //如果数据为空或为NULL的时候，跳过此次循环进入下一次循环
            if (null == obj.getValue() || "" == obj.getValue()) {
                continue;
            }
            sql.append(" and " + obj.getKey() + " like '%" + obj.getValue() + "%'");

        }

        sql.append(" order by " + sort + " " + order);

        Page<Resource> descPage = this.paginate(page, rows, getSql(SQL_SELECT_COMM), sql.toString());

        return descPage;
    }


    public List<Resource> findList(Resource resource) {
        StringBuffer sql = new StringBuffer();

        sql.append("select * from t_resource where resource_id=resource_id ");

        Iterator i = resource._getAttrsEntrySet().iterator();

        //循环遍历传过来的参数，并将参数拼接到SQL
        while (i.hasNext()) {
            Map.Entry<String, Object> obj = (Map.Entry<String, Object>) i.next();

            if (StrKit.isBlank(obj.getKey())) continue;

            if (StringUtils.equalsIgnoreCase("resource_id", obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase("pid", obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            //如果数据为空或为NULL的时候，跳过此次循环进入下一次循环
            if (null == obj.getValue() || "" == obj.getValue()) {
                continue;
            }
            sql.append(" and " + obj.getKey() + " like '%" + obj.getValue() + "%'");

        }


        return this.find(sql.toString());
    }


    public void getResourceIdList(StringBuilder resourceIdSb, String resourceId, boolean bool) {
        List<Resource> resourceList = Resource.dao.findList(new Resource().set(DBCommon.TABLE_RESOURCE_COLUMN_PID, resourceId));
        for (Resource resource : resourceList) {
            if (bool) {//bool为true的时候在字符串两边添加单引号
                resourceIdSb.append("'");
            }

            resourceIdSb.append(resource.getResourceId());

            if (bool) {//bool为true的时候在字符串两边添加单引号
                resourceIdSb.append("'");
            }
            resourceIdSb.append(SystemConst._DEFAULT_SEPARATOR_COMMA);

            Resource.dao.getResourceIdList(resourceIdSb, resource.getResourceId(), bool);
        }
    }


    /**
     * 获取所以资源信息
     *
     * @return
     */
    public List<Resource> findAll() {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT resource_id,pid,resource_name,url,resource_type,icon,des,createts,updatets,is_enable,order_number FROM t_resource order by order_number");
        List<Resource> resources = this.find(sql.toString());
        return resources;
    }


    /**
     * 根据角色ID联合查询得到资源信息和节点选中状态
     *
     * @param roleId 角色ID
     * @return
     */
    public List<Resource> findResourceAndCheckStateByRoleId(String roleId, String isEnable) {
        StringBuilder sql = new StringBuilder();
        sql.append("select resource_id,resource_name,pid,url,icon,des,order_number,createts,updatets,(select check_state from t_resource_role where resource_id= t_resource.resource_id and role_id = ?) as check_state from t_resource where resource_id =resource_id ");
        if (!StrKit.isBlank(isEnable)) {
            sql.append(" and is_enable = '" + isEnable + "'");
        }
        sql.append(" order by order_number");
        return this.find(sql.toString(), roleId);
    }

    /**
     * 根据角色ID获取资源列表
     *
     * @param roleId 角色ID
     * @return 资源列表
     */
    public List<Resource> findByRoleId(String roleId) {
        StringBuffer sql = new StringBuffer();

        LOG.info("获取到的角色ID为：" + roleId);

        sql.append("SELECT " +
                " a.resource_id, " +
                " a.pid, " +
                " a.resource_name, " +
                " a.url, " +
                " a.resource_type, " +
                " a.icon, " +
                " a.des, " +
                " a.updatets, " +
                " ( " +
                "  SELECT " +
                "   rr_id " +
                "  FROM " +
                "   t_resource_role " +
                "  WHERE " +
                "   resource_id = a.resource_id " +
                "  AND role_id = ? " +
                " ) AS rr_id " +
                "FROM " +
                " t_resource a " +
                "ORDER BY " +
                " a.order_number");


        return this.find(sql.toString(), roleId);
    }


    /**
     * 根据用户ID获取资源列表
     *
     * @param userId 角色ID
     * @return 资源列表
     */
    public List<Resource> findByUserIdAndType(String userId, int type) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT resource_id,pid,resource_name,url,resource_type,icon,des,updatets FROM t_resource WHERE resource_id IN (SELECT DISTINCT resource_id FROM t_resource_role WHERE role_id IN (SELECT role_id FROM t_user_role WHERE user_id = ?)) and resource_type = ? ORDER BY order_number");
        return this.find(sql.toString(), userId, type);
    }

    /**
     * 根据用户ID获取资源列表
     *
     * @param userId 角色ID
     * @return 资源列表
     */
    public List<Resource> findByUserId(String userId) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT resource_id,pid,resource_name,url,resource_type,icon,des,updatets FROM t_resource WHERE resource_id IN (SELECT DISTINCT resource_id FROM t_resource_role WHERE role_id IN (SELECT role_id FROM t_user_role WHERE user_id = ?)) ORDER BY order_number");
        return this.find(sql.toString(), userId);
    }


    public List<Resource> findByUserIdAndType(String userId, int type, String pid) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT resource_id,pid,resource_name,url,resource_type,icon,des,updatets FROM t_resource WHERE resource_id IN (SELECT DISTINCT resource_id FROM t_resource_role WHERE role_id IN (SELECT role_id FROM t_user_role WHERE user_id = ?)) and resource_type = ? and pid = ? ORDER BY order_number");
        return this.find(sql.toString(), userId, type, pid);
    }


    /**
     * 获取资源总记录数
     *
     * @return
     */
    public int count() {
        String sql = "SELECT COUNT(*) AS resource_count FROM t_resource";
        return Db.queryInt(sql);
    }

    /**
     * 根据资源名获取资源信息
     *
     * @param name 资源名称
     * @return User 资源信息
     */
    public Resource getResourceByName(String name) {
        return this.findFirst("SELECT * FROM t_resource WHERE resource_name = ?", name);
    }


    public String findChildIds(String ids) {
        String returnIds = "";
        StringBuffer sql = new StringBuffer();

        String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        ids = "";
        for (int i = 0; i < idArr.length; i++) {
            ids = "'" + idArr[i] + "'";
            if (i != idArr.length - 1) {
                ids += ",";
            }
        }

		/*sql.append("with cte as   " +
                " (   " +
				" select a.resource_id from t_resource a where [pid] IN (" +
				ids + ")   " +
				" union all    " +
				" select k.resource_id from t_resource k inner join cte c on c.resource_id = k.pid   " +
				" ) select * from cte  ");*/

        sql.append("SELECT RESOURCE_ID " +
                "FROM T_RESOURCE " +
                "START WITH PID IN (" + ids + ") " +
                "CONNECT BY PRIOR RESOURCE_ID=PID");

        List<Resource> resourceList = this.find(sql.toString());//获取ID参数的所有子节点ID
        if (null != resourceList) {
            for (Resource resource : resourceList) {
                returnIds += resource.getResourceId() + ",";
            }
        }
        return returnIds;
    }

    public List<Resource> findAllResourceByRoleId(String roleId) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT * FROM t_resource WHERE resource_id IN (SELECT RESOURCE_ID FROM t_resource_role WHERE role_id = ?)order by order_number");
        return find(sql.toString(), roleId);
    }

    public List<Resource> findByUserIdAndPid(String userId, String pid) {
        List<Resource> resourceList = this.find(getSql(SQL_SELECT_USERID_PID), userId, pid);
        return resourceList;
    }

}
